/**
 * @author: akolonitsky
 * @date: 11/29/11 1:45 PM
 */
package view {
import flash.display.Loader;
import flash.errors.IOError;
import flash.events.Event;
import flash.events.IOErrorEvent;
import flash.net.FileFilter;
import flash.net.FileReference;
import flash.system.ApplicationDomain;
import flash.system.LoaderContext;
import flash.system.SecurityDomain;
import flash.utils.ByteArray;

import model.UserProxy;
import model.vo.LogRecord;

import model.vo.UserVO;

import mx.core.FlexGlobals;

import org.kolonitsky.alexey.debug.DebugWrapper;

import org.puremvc.as3.interfaces.INotification;

import org.puremvc.as3.patterns.mediator.Mediator;

import spark.components.Application;

import view.events.DataSetEvent;

public class ImportMediator extends Mediator
{
    public static const NAME:String = "importMediator";

    public function ImportMediator()
    {
        super(NAME, null)
    }

    public function get app():Elfin
    {
        return FlexGlobals.topLevelApplication as Elfin;
    }

    //-------------------------------------------------------------------------
    //
    //  Override mediator
    //
    //-------------------------------------------------------------------------

    override public function onRegister():void
    {
        super.onRegister();
        app.addEventListener(DataSetEvent.IMPORT, app_exportHandler);
    }

    override public function onRemove():void
    {
        app.removeEventListener(DataSetEvent.IMPORT, app_exportHandler);
        super.onRemove();
    }

    override public function listNotificationInterests():Array
    {
        return [
            UserProxy.USER_AUTHORIZATION
        ];
    }

    override public function handleNotification(notification:INotification):void
    {
        super.handleNotification(notification);
        switch (notification.getName())
        {
            case UserProxy.USER_AUTHORIZATION:
            {
                if (notification.getBody())
                    user = notification.getBody() as UserVO;
                break;
            }
        }
    }




    //-------------------------------------------------------------------------
    //
    // Private logic
    //
    //-------------------------------------------------------------------------

    private var fr:FileReference = null;

    private var user:UserVO = null;

    private function app_exportHandler(event:DataSetEvent):void
    {
        var csvType:FileFilter = new FileFilter("CSV Table", "*.csv");

        fr = new FileReference();
        fr.addEventListener(Event.COMPLETE, fr_completeHandler);
        fr.addEventListener(Event.SELECT, fr_selectHandler);
        fr.browse([csvType]);
    }

    private function fr_completeHandler(event:Event):void
    {
        DebugWrapper.trace("DEBUG: fr_completeHandler!");

        fr.data.position = 0;
        var csv:String = fr.data.readMultiByte(fr.data.bytesAvailable, "utf-8");

        var records:Array = parsCSV(csv);

        var tweetLines:String = "";
        for (var i:int = 0; i < records.length; i++)
        {
            var record:LogRecord = records[i];
            var dateString:String = [record.date.fullYear, record.date.month, record.date.date].join("-");
            tweetLines += dateString + " " + record.valueToString() + " " + record.comment + "\n";
        }

        sendNotification(Config.RECORD_ADD, tweetLines, "reload");
    }

    /**
     *
     * @param scv
     * @return
     */
    private function parsCSV(csv:String):Array
    {
        var lines:Array = csv.split("\n");

        var header:Array = String(lines[0]).split(",");
        var n:int = lines.length;

        DebugWrapper.trace("DEBUG: header = " + header);
        DebugWrapper.trace("DEBUG: n = " + n);

        var result:Array = [];

        for (var i:int = 1; i < n; i++)
        {
            var cels:Array = String(lines[i]).split(",");
            if (cels.length < 3)
                continue;
            
            var dateArray:Array = String(cels[0]).split("-");

            var record:LogRecord = new LogRecord();
            record.date = dateArray && dateArray.length 
                ? new Date(dateArray[0], dateArray[1], dateArray[2])
                : new Date(cels[0]);
            record.comment = String(cels[1]);
            record.value = {};
            for (var j:int = 2, c:int = 0; j < cels.length; j++, c++)
                if (cels[j])
                    record.value[header[j]] = cels[j];

            result.push(record);
        }

        return result;
    }

    private function loader_ioErrorHandler(event:IOErrorEvent):void
    {
        DebugWrapper.trace("DEBUG: loader_completeHandler");
        DebugWrapper.trace("ERROR: " + event.text);
    }

    private function fr_selectHandler(event:Event):void
    {
        DebugWrapper.trace("DEBUG: fr_selectHandler!");
        fr.load();
    }
}
}
